import axios from './interceptor'
import Qs from 'qs'
import config from '../config'

const JSON_HEADER =  'application/json; charset=UTF-8'
const FORMDATA_HEADER = 'application/x-www-form-urlencoded; charset=UTF-8'
const MULTIPART_HEADER = 'multipart/form-data; charset=UTF-8'

// axios的content-type是自动设置的
// 如果当 data 为 URLSearchParams 对象时，设置为 application/x-www-form-urlencoded;charset=utf-8, 
// 如果当 data 为普通对象时，设置为 application/json;charset=utf-8
// 也可以在post请求里面设置transformRequest，content-type 等于 application/x-www-form-urlencoded

let webUrl = config.webUrl

class Services {
  // get请求
  get (api, params) {
    return axios({
      method: 'get',
      url: api,
      params: params      // 这里要注意，key不是data
    })
  }

  // post请求
  post (api, params, isJson = 0, timeout = 30000) {
    return axios({
      method: 'post',
      url: webUrl + api,
      data: params,
      headers: {
        'Content-Type':  isJson === 1 ? JSON_HEADER : FORMDATA_HEADER,
      },
      transformRequest: [function (data) {
        // json 格式
        if (isJson === 1) {
          return JSON.stringify(data)
        }

        // formData 格式
        let ret = Qs.stringify(data)
        return ret
      }],
      timeout
    })
  }

  // 上传请求
  upload (api, params) {
    return axios({
      method: 'post',
      url: webUrl + api,
      data: params,
      headers: {
        'Content-Type': MULTIPART_HEADER,
      },
      withCredentials: true
    })
  }
}
export default new Services()
